﻿using System;
using System.ComponentModel;
using Microsoft.SharePoint;
using VPLink2013.Framework;
using VPLink2013.Framework.Constants;
using VPLink2013.Framework.Extensions;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.Utilities;
using System.IO;

namespace VPLink2013.Webpart
{
    public class MercureChantiersList : WebpartVPLink
    {
        #region get HTML
        /// <summary>
        /// Returns the HTML code rendered by this web part
        /// </summary>
        /// <returns>HTL code as string</returns>
        protected override string GetHtml()
        {
            string strHtml = string.Empty;
            ContextTrace.PrefixFileName = "webpart MercureProjetsList";

            string strHtmlFileCache = string.Empty;

            try
            {
                global = new GlobalVPLink2013();
                global.ListeAnnonces = new List<Annonce>();

                Uri paramSiteUri = new Uri(ParamSharepointSite);
                Uri mercureSiteUri = new Uri(paramSiteUri, "/services/production/Mercure");
                string strUrl = mercureSiteUri.AbsoluteUri;

                ContextTrace.AddTrace("strUrl : " + strUrl);
                
                string strXslFileName = string.Empty;
                
                using (SPSite site = new SPSite(strUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        ContextTrace.PrefixFileName = "Mercure - Les chantiers";
                        string strList = "Les projets";
                        ContextTrace.AddTrace("strList : " + strList);
                        SPList lst = web.Lists.TryGetList(strList);

                        string strID = ParamFrm("ItemID");
                        if (string.IsNullOrEmpty(strID))
                        {
                            strID = ParamFrm("ID");
                        }
                        if (string.IsNullOrEmpty(strID))
                        {
                            strXslFileName = "MercureChantiers.xsl";
                            if (lst != null)
                            {
                                ProcessChantiers(lst, strUrl);
                            }
                        }
                        else
                        {
                            strXslFileName = "MercureChantierDetail.xsl";
                            if (lst != null)
                            {
                                ProcessChantierDetail(lst, strID, strUrl);
                            }
                        }
                    }

                    string strXml = FileSerialization.CreateXmlStringFromObj(global);

                    string strXslPath = Path.Combine(pathVP,"XSL","NewsVP",strXslFileName);
                    ContextTrace.AddTrace("GetHtml.strXslPath = " + strXslPath);
                    strHtml = VPLink2013XsltTransformHelper.GetTransform(strXml, strXslPath, StringAfter(UtilisateurCrt.Login), pathTemp);
                }
            }
            catch (System.Exception exc)
            {
                ContextTrace.AddTrace("Erreur GetHtml : " + exc.Message + "/" + exc.StackTrace);
            }
            return strHtml;
        }
        #endregion get HTML

        private void ProcessChantiers(SPList lst, string siteUrl)
        {
            string strListe = lst.Title;
            SPQuery spQuery = new SPQuery();
            StringBuilder sb = new StringBuilder();

            MenuInterneAnnonce mei = new MenuInterneAnnonce();
            //mei.MyTrace = MyTrace;

            global.Filtre = new Filtre();
            global.Filtre.Titre = ParamFrm("FiltreNewsTitre");
            if (global.Filtre.Titre == "Rechercher un chantier")
            {
                global.Filtre.Titre = string.Empty;
            }

            string strDateCrt = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now);
            if (!string.IsNullOrEmpty(global.Filtre.Titre))
            {
                sb.Append("<Where>");
                sb.AppendLine("<Or>");
                sb.AppendLine("     <Contains><FieldRef Name='Title'/><Value Type='Text'>" + global.Filtre.Titre + "</Value></Contains>");
                sb.AppendLine("     <Contains><FieldRef Name='Description'/><Value Type='Text'>" + global.Filtre.Titre + "</Value></Contains>");
                sb.AppendLine("</Or>");
                sb.AppendLine("</Where>");
            }
            sb.AppendLine("<OrderBy><FieldRef Name='Title'/><FieldRef Name='ID' Ascending='FALSE'/></OrderBy>");

            if (string.IsNullOrEmpty(global.Filtre.Titre))
            {
                global.Filtre.Titre = "Rechercher un chantier";
            }

            string Query = sb.ToString();
            spQuery.Query = Query;
            ContextTrace.AddTrace("spQuery.Query : " + spQuery.Query);

            SPListItemCollection items = lst.GetItems(spQuery);
            ContextTrace.AddTrace("items.Count : " + items.Count.ToString());

            string strPageCrt = ParamFrm("PageCrt");

            int iPageCrt = 1;
            if (!string.IsNullOrEmpty(strPageCrt))
            {
                iPageCrt = int.Parse(strPageCrt);
            }
            global.Filtre.PageCrt = GetControlHidden("PageCrt", iPageCrt.ToString());

            int iPagePrec = 0;
            int iPageSuiv = 0;

            int iNbPerPage = 10;

            int iCrt = 1;
            int iStart = (iPageCrt - 1) * iNbPerPage + 1;
            int iEnd = iPageCrt * iNbPerPage;

            ContextTrace.AddTrace("iStart : " + iStart.ToString());
            ContextTrace.AddTrace("iEnd : " + iEnd.ToString());

            foreach (SPListItem item in items)
            {
                try
                {
                    ContextTrace.AddTrace("iCrt : " + iCrt.ToString());
                    if (iCrt < iStart)
                    {
                        iPagePrec = iPageCrt - 1;
                        ContextTrace.AddTrace("iPagePrec : " + iPagePrec.ToString());
                    }
                    if (iCrt > iEnd)
                    {
                        iPageSuiv = iPageCrt + 1;
                        ContextTrace.AddTrace("iPageSuiv : " + iPageSuiv.ToString());
                    }
                    if (iCrt >= iStart && iCrt <= iEnd)
                    {
                        ContextTrace.AddTrace("-------------------------------");
                        Annonce ann = CreateAnnonceFromItem(item, siteUrl);
                        ann.Ordre = (iCrt % 2).ToString();
                        global.ListeAnnonces.Add(ann);
                    }
                }
                catch (Exception ex)
                {
                    ContextTrace.AddTrace("Exception lors de la création d'une annonce");
                    ContextTrace.AddTrace(ex.Message);
                    ContextTrace.AddTrace(ex.StackTrace);
                }
                iCrt += 1;
            }

            if (iPagePrec > 0 || iPageSuiv > 0)
            {
                StringBuilder sbNavigationPages = new StringBuilder();
                sbNavigationPages.AppendLine("<div class=\"pages_news\">");

                if (iPagePrec > 0)
                {
                    sbNavigationPages.AppendLine("<a href=\"javascript:GoToPage(" + iPagePrec.ToString() + ");\">");
                    sbNavigationPages.AppendLine("<img src=\"/_layouts/VentePrivee2013/Images/pages_news_left.jpg\" width=\"6\" height=\"11\" border='0'>");
                    sbNavigationPages.AppendLine("   Page précédente");
                    sbNavigationPages.AppendLine("</a>");
                }
                if (iPagePrec > 0 && iPageSuiv > 0)
                {
                    sbNavigationPages.AppendLine("<span>|</span>");
                }
                if (iPageSuiv > 0)
                {
                    sbNavigationPages.AppendLine("<a href=\"javascript:GoToPage(" + iPageSuiv.ToString() + ");\">");
                    sbNavigationPages.AppendLine("Page suivante   ");
                    sbNavigationPages.AppendLine("<img src=\"/_layouts/VentePrivee2013/Images/pages_news_right.jpg\" width=\"6\" height=\"11\" border='0'>");
                    sbNavigationPages.AppendLine("</a>");
                }
                sbNavigationPages.AppendLine("</div>");

                global.Filtre.NavigationPages = sbNavigationPages.ToString();
                global.Filtre.NavigationPagesBottom = sbNavigationPages.ToString().Replace("\"pages_news\"", "\"pages_news pages-bottom\"");
                ContextTrace.AddTrace("global.Filtre.NavigationPages : " + global.Filtre.NavigationPages);
            }
        }

        private static Annonce CreateAnnonceFromItem(SPListItem item, string siteUrl)
        {
            Annonce ann = new Annonce();
            ann.ID = item.ID.ToString();
            Uri siteUri = new Uri(siteUrl);
            Uri detailUri = new Uri(siteUri, "/Pages/ChantierDetail.aspx?ItemID=" + ann.ID);
            ann.LinkDetail = detailUri.AbsoluteUri;
            ann.Titre = item.GetItemListFieldValueAsText(Fields.TitleField);
            ann.TitrePiwik = ann.Titre.Replace("/", "-").Replace("'", "\\'").Replace("\"", "\\'");
            ann.Chapeau = item.GetItemListFieldValueAsHtml(Fields.DescriptionField);
            ann.Photo1 = item.GetItemListFieldValueAsUrlValue(Fields.PhotoField);

            ContextTrace.AddTrace("ann.ID : " + ann.ID);
            ContextTrace.AddTrace("ann.Titre : " + ann.Titre);
            ContextTrace.AddTrace("ann.Chapeau : " + ann.Chapeau);
            ContextTrace.AddTrace("ann.Ordre : " + ann.Ordre);
            ContextTrace.AddTrace("ann.Photo1 : " + ann.Photo1);
            return ann;
        }

        private void ProcessChantierDetail(SPList lst, string strID, string siteUrl)
        {
            try
            {
                int idChantier = int.Parse(strID);
                SPListItem item = lst.Items.GetItemById(idChantier);
                Annonce ann = CreateAnnonceFromItem(item, siteUrl);
                global.ListeAnnonces.Add(ann);
            }
            catch (System.Exception exc)
            {
                ContextTrace.AddTrace("Error.ProcessChantierDetail : " + exc.Message + "/" + exc.StackTrace);
            }
        }
    }
}
